import 'dart:async';
import 'package:in_app_purchase/in_app_purchase.dart';

class PayUtils {
  // 单例
  static final PayUtils _instance = PayUtils._internal();
  factory PayUtils() => _instance;
  PayUtils._internal();

  // 商品ID
  static const String _subscriptionWeekly = 'com.glimv1.ios.vip.wk.9_99';
  static const String _subscriptionMonthly = 'com.glimv1.ios.vip.mo.19_99';
  static const String _subscriptionQuarterly = 'com.glimv1.ios.vip.qtr.29_99';
  static const String _subscriptionYearly = 'com.glimv1.ios.vip.ann.69_99';
  static const String _nonConsumable = 'com.glimv1.ios.prem.4_99';
  static const String _consumablePic1 = 'com.glimv1.ios.pri_pic.1x.4_99';
  static const String _consumablePic5 = 'com.glimv1.ios.pri_pic.5x.14_99';
  static const String _consumablePic10 = 'com.glimv1.ios.pri_pic.10x.19_99';
  static const String _consumablePic30 = 'com.glimv1.ios.pri_pic.30x.49_99';
  static const String _consumableVid1 = 'com.glimv1.ios.pri_vid.1x.6_99';
  static const String _consumableVid5 = 'com.glimv1.ios.pri_vid.5x.19_99';
  static const String _consumableVid10 = 'com.glimv1.ios.pri_vid.10x.29_99';
  static const String _consumableVid30 = 'com.glimv1.ios.pri_vid.30x.79_99';

  static const List<String> _kProductIds = <String>[
    _subscriptionWeekly,
    _subscriptionMonthly,
    _subscriptionQuarterly,
    _subscriptionYearly,
    _nonConsumable,
    _consumablePic1,
    _consumablePic5,
    _consumablePic10,
    _consumablePic30,
    _consumableVid1,
    _consumableVid5,
    _consumableVid10,
    _consumableVid30,
  ];

  static final Set<String> _kConsumableProductIds = <String>{
    _consumablePic1,
    _consumablePic5,
    _consumablePic10,
    _consumablePic30,
    _consumableVid1,
    _consumableVid5,
    _consumableVid10,
    _consumableVid30,
  };

  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  List<ProductDetails> _products = <ProductDetails>[];

  // 初始化
  Future<void> init() async {
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription = purchaseUpdated.listen(
      (List<PurchaseDetails> purchaseDetailsList) {
        _listenToPurchaseUpdated(purchaseDetailsList);
      },
      onDone: () {
        _subscription.cancel();
      },
      onError: (Object error) {
        // 在这里处理错误。
      },
    );

    await _loadProducts();
  }

  // 获取商品信息
  Future<void> _loadProducts() async {
    final bool available = await _inAppPurchase.isAvailable();
    if (!available) {
      // 无法访问或使用商店。相应地更新UI。
      return;
    }

    final ProductDetailsResponse response = await _inAppPurchase
        .queryProductDetails(_kProductIds.toSet());
    if (response.error != null) {
      // 在这里处理查询产品错误。
      return;
    }

    if (response.productDetails.isEmpty) {
      // 没有可购买的产品。
      return;
    }

    _products = response.productDetails;
  }

  // 监听购买更新
  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) {
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      if (purchaseDetails.status == PurchaseStatus.pending) {
        // 在这里处理待处理的购买。
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          // 在这里处理错误。
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          // 在这里处理已购买或已恢复的购买。
          // 您应该与您的服务器验证购买。
        }
        if (purchaseDetails.pendingCompletePurchase) {
          _inAppPurchase.completePurchase(purchaseDetails);
        }
      }
    }
  }

  // 发起购买
  Future<void> purchase(ProductDetails productDetails) async {
    final PurchaseParam purchaseParam = PurchaseParam(
      productDetails: productDetails,
    );
    if (_kConsumableProductIds.contains(productDetails.id)) {
      await _inAppPurchase.buyConsumable(purchaseParam: purchaseParam);
    } else {
      await _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam);
    }
  }

  // 恢复购买
  Future<void> restorePurchases() async {
    await _inAppPurchase.restorePurchases();
  }

  // 获取产品列表
  List<ProductDetails> get products => _products;

  // 清理资源
  void dispose() {
    _subscription.cancel();
  }
}
